﻿using Microsoft.Extensions.DependencyInjection;
using Modules;
using PmSoft.Events;
using PmSoft.Logging;

namespace PmSoft.Repositories;

[UseDI(ServiceLifetime.Singleton, typeof(IEventMoudle))]
public class EntityEventModule : IEventMoudle
{
    private readonly IEventBus eventBus;

    public EntityEventModule(IEventBus eventBus)
    {
        this.eventBus = eventBus;
    }

    public void RegisterEventHandler()
    {
        eventBus.Subscribe<EntityEventArgs, EntityEventHandler>();
    }
}

[UseDI(ServiceLifetime.Scoped)]
public class EntityEventHandler : IEventHandler<EntityEventArgs>
{
    private readonly SysTableLogService tableLogService;

    public EntityEventHandler(SysTableLogService tableLogService)
    {
        this.tableLogService = tableLogService;
    }


    public Task HandleAsync(object sender, EntityEventArgs eventArgs)
    {
        if (eventArgs.Entity is SysTableLog)
            return Task.CompletedTask;

        tableLogService.Create(eventArgs);
        return Task.CompletedTask;
    }
}
